package com.nwu.records.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nwu.common.result.Result;
import com.nwu.records.domain.*;
import com.nwu.records.domain.vo.EmotionDetailsVo;
import com.nwu.records.domain.vo.EmotionRecordsVo;
import com.nwu.records.domain.vo.PhyDetailsVo;
import com.nwu.records.domain.vo.PhyRecordsVo;
import com.nwu.records.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/records")
@Api(tags = "记录")
@Slf4j
@RequiredArgsConstructor
public class RecordsController {

    private final UserDateRecordsService userDateRecordsService;
    private final EmotionRecordsService emotionRecordsService;
    private final PhysiologyRecordsService physiologyRecordsService;
    private final EmotionCategoriesService emotionCategoriesService;
    private final PhysiologyCategoriesService physiologyCategoriesService;
    private final EmotionDetailsService emotionDetailsService;
    private final PhysiologyDetailsService physiologyDetailsService;


    @ApiOperation("查询 所有晴雨表选项")
    @GetMapping("/allEmotion")
    public Result getEmotion() {
        List<EmotionCategories> categories = emotionCategoriesService.list();
        ArrayList<List> emotionsList = new ArrayList<>();
        for (EmotionCategories c : categories) {
            LambdaQueryWrapper<EmotionDetails> queryWrapper = new LambdaQueryWrapper<EmotionDetails>()
                    .select().eq(EmotionDetails::getEmotionCategoriesId, c.getId());
            List<EmotionDetails> emotionList = emotionDetailsService.list(queryWrapper);
            emotionsList.add(emotionList);
        }
        EmotionDetailsVo detailsVo = new EmotionDetailsVo();
        detailsVo.setCategories(categories);
        detailsVo.setEmotionDetails(emotionsList);
        return Result.success(detailsVo);
    }

    @ApiOperation("查询 所有生理明细表选项")
    @GetMapping("/allPhy")
    public Result getPhy() {
        List<PhysiologyCategories> categories = physiologyCategoriesService.list();
        ArrayList<List> phyLists = new ArrayList<>();
        for (PhysiologyCategories c : categories) {
            LambdaQueryWrapper<PhysiologyDetails> queryWrapper = new LambdaQueryWrapper<PhysiologyDetails>()
                    .select().eq(PhysiologyDetails::getPhysiologyCategoriesId, c.getId());
            List<PhysiologyDetails> phyList = physiologyDetailsService.list(queryWrapper);
            phyLists.add(phyList);
        }
        PhyDetailsVo detailsVo = new PhyDetailsVo();
        detailsVo.setCategories(categories);
        detailsVo.setPhyDetails(phyLists);
        return Result.success(detailsVo);
    }

//    @ApiOperation("查询 用户所有记录")
//    @GetMapping("/allUserRecords")
//    public Result geUserRecords() {
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        Long userId = (Long) authentication.getPrincipal();
//        LambdaQueryWrapper<UserDateRecords> queryWrapper = new LambdaQueryWrapper<UserDateRecords>()
//                .select().eq(UserDateRecords::getUserId, userId);
//        List<UserDateRecords> dateList = userDateRecordsService.list(queryWrapper);
//        List<EmotionOption> emotionOptionList = emotionOptionService.list();
//
//        ArrayList<RecordsVo> recordsVos = new ArrayList<>();
//
//        for (UserDateRecords date : dateList) {
//
//            LambdaQueryWrapper<EmotionRecords> queryWrapper1 = new LambdaQueryWrapper<EmotionRecords>()
//                    .select().eq(EmotionRecords::getDateId, date.getId());
//            List<EmotionRecords> emotionRecordsList = emotionRecordsService.list(queryWrapper1);
//            ArrayList<EmotionRecords> emotionRecords = new ArrayList<>();
//            List<String> emotionImgList = new ArrayList<>();
//            Integer emotionScore = 0;
//            List<String> emotionList = new ArrayList<>();
//            for (EmotionRecords emotionRecord : emotionRecordsList) {
//                Optional<EmotionOption> emotionOption = emotionOptionList.stream()
//                        .filter(a -> a.getId() == emotionRecord.getEmotionOptionId() )
//                        .findFirst();
//                emotionList.add(emotionOption.get().getEmotion());
//                emotionImgList.add(emotionOption.get().getImgUrl());
//                emotionScore += emotionOption.get().getScore();
//            }
//            RecordsVo recordsVo = RecordsVo.builder()
//                    .build();
//
//        }
//        return Result.success();
//    }

    @SneakyThrows
    @ApiOperation("存储 晴雨表信息")
    @PostMapping("/saveEmotion")
    public Result saveEmotion(@RequestBody EmotionRecordsVo emotionRecordsVo) {
        Date currentTime = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date today = ft.parse(new SimpleDateFormat("yyyy-MM-dd").format(currentTime));
        SimpleDateFormat tm = new SimpleDateFormat("a");
        int tms = 1;
        if ("下午".equals(tm.format(currentTime))) {
            tms = 2;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = (Long) authentication.getPrincipal();
//        Long userId = Long.parseLong("15");
        LambdaQueryWrapper<UserDateRecords> queryWrapper = new LambdaQueryWrapper<UserDateRecords>()
                .select(UserDateRecords::getId).eq(userId != null, UserDateRecords::getUserId, userId)
                .eq(UserDateRecords::getDate, today)
                .eq(UserDateRecords::getTime,tms);
        UserDateRecords date = userDateRecordsService.getOne(queryWrapper); // 调用 getOne 方法

        log.info(String.valueOf(emotionRecordsVo));
        if (date == null) {
            UserDateRecords new_date = new UserDateRecords();
            new_date.setDate(today);
            new_date.setTime(tms);
            new_date.setUserId(userId);
            userDateRecordsService.save(new_date);
            date = new_date;
        }
        for (Long id : emotionRecordsVo.getEmotionSelected()) {
            EmotionRecords emotionRecords = new EmotionRecords();
            emotionRecords.setUserDateRecordsId(date.getId());
            emotionRecords.setEmotionDetailsId(id);
            try {
                emotionRecordsService.save(emotionRecords);
            } catch (Exception e) {
                return Result.error("重复插入！");
            }
        }
        return Result.success();
    }

    ;

    @SneakyThrows
    @ApiOperation("存储 生理情况信息")
    @PostMapping("/savePhy")
    public Result savePhy(@RequestBody PhyRecordsVo phyRecordsVo) {
        Date currentTime = new Date();
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
        Date today = ft.parse(new SimpleDateFormat("yyyy-MM-dd").format(currentTime));
        SimpleDateFormat tm = new SimpleDateFormat("a");
        int tms = 1;
        if ("下午".equals(tm.format(currentTime))) {
            tms = 2;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Long userId = (Long) authentication.getPrincipal();
//        Long userId = Long.parseLong("15");
        LambdaQueryWrapper<UserDateRecords> queryWrapper = new LambdaQueryWrapper<UserDateRecords>()
                .select(UserDateRecords::getId).eq(userId != null, UserDateRecords::getUserId, userId)
                .eq(UserDateRecords::getDate, today)
                .eq(UserDateRecords::getTime,tms);
        UserDateRecords date = userDateRecordsService.getOne(queryWrapper); // 调用 getOne 方法
        log.info(String.valueOf(date));
        if (date == null) {
            UserDateRecords new_date = new UserDateRecords();
            new_date.setDate(today);
            new_date.setUserId(userId);
            new_date.setTime(tms);
            userDateRecordsService.save(new_date);
            date = new_date;
        }
        for (Long id : phyRecordsVo.getPhySelected()) {
            PhysiologyRecords phyRecords = new PhysiologyRecords();
            phyRecords.setUserDateRecordsId(date.getId());
            phyRecords.setPhysiologyDetailsId(id);
            try {
                physiologyRecordsService.save(phyRecords);
            } catch (Exception e) {
                return Result.error("重复插入！");
            }
        }
        return Result.success();
    }

    ;
}
